import storage from "@/store/storage";

//工具类方法的配置
import { Notification, MessageBox, Loading } from "element-ui";

//控制按钮显隐power：按钮权限code
let btnShow = function (power) {
  let powers = storage.getPowers();
  var flag = false;
  powers.forEach(e => {
    if (e == power) {
      flag = true;
    }
  });
  return flag;
};

//提示信息封装
let notify = {
  success: function (message, duration) {
    Notification.success({
      title: "成功",
      message: message || "",
      duration: duration || 3000
    });
  },
  warning: function (message, duration) {
    Notification.warning({
      title: "提醒",
      message: message,
      duration: duration || 3000
    });
  },
  error: function (message, duration) {
    Notification.error({
      title: "错误",
      message: message,
      duration: duration || 3000
    });
  },
  holdMsg: function (message) {
    Notification.info({
      title: "提示",
      message: message,
      duration: 0
    });
  }
};

// 弹框提示
let msgbox = {
  alert: function (message) {
    MessageBox.alert(message, "提示", {
      confirmButtonText: "确定"
    });
  },
  info: function (message, callback) {
    MessageBox.alert(message, "提示", {
      confirmButtonText: "确定",
      type: "info",
      callback: action => {
        callback && callback();
      }
    });
  },
  success: function (message, callback) {
    MessageBox.alert(message, "提示", {
      confirmButtonText: "确定",
      type: "success",
      callback: action => {
        callback && callback();
      }
    });
  },
  warning: function (message, callback) {
    MessageBox.alert(message, "提示", {
      confirmButtonText: "确定",
      type: "warning",
      callback: action => {
        callback && callback();
      }
    });
  },
  confrim: function (message, callback, cancleback) {
    MessageBox.confirm(message, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      callback && callback();
    }).catch(err => {
      cancleback && cancleback(err);
    });
  }
};

// 加载进度条 
// 使用闭包创建，防止loadCount被篡改。
let loading = (function () {
  // 为了解决多个请求进行时，会造成多次显示遮罩，闪屏的问题
  var loadCount = 0;

  // 打开全局的loading
  function show(text) {
    Loading.service({
      fullscreen: true,
      text: text,
      background: 'rgba(0, 0, 0, 0.5)'  // 黑色，半透明
    });
    loadCount += 1;
  }

  // 关闭全局的loading
  function hide() {
    loadCount -= 1;

    if (loadCount > 0) {
      return;
    }
    var loadObj = Loading.service({ fullscreen: true });
    loadObj.close();
  }

  return { show, hide };
})();

//表单校验
let formRules = {
  telPhone: {  //手机号/电话号校验
    regex: /^(((0\d{2,3})-)(\d{7,8})(-(\d{3,4}))?|(1[35678]\d{9})|([0-9]{3,4})?(-)?[0-9]{7})$/,
    msg: "请输入正确格式的手机号/电话",
  },
  idCard: {  //身份证校验
    regex: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
    msg: "请输入正确格式的身份证号"
  },
  serverAddress: {  //服务器地址
    regex: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
    msg: "请输入合法的服务器地址"
  },
  nonnegativeInt: {  //非负整数
    regex: /^[1-9]\d*|0$/,
    msg: "请输入大于等于0的整数",
  },
  monnegativeNumber: {  //非负数
    regex: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{1,2})$/,
    msg: "请输入大于等于0的数字(保留两位小数)"
  },
  positiveNumber: {  //正数
    regex: /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/,
    msg: "请输入大于0的数字(保留两位小数)"
  },
  positiveInt: {  //正整数
    regex: /^[0-9]*[1-9][0-9]*$/,
    msg: "请输入正整数"
  },
  plateNumber: {  //车牌号校验
    regex: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
    msg: "车牌号格式不正确"
  }
};

//克隆
let clone_str = function (obj) {
  var o;
  switch (typeof obj) {
    case "undefined":
      break;
    case "string":
      o = obj + "";
      break;
    case "number":
      o = obj - 0;
      break;
    case "boolean":
      o = obj;
      break;
    case "object":
      if (obj === null) {
        o = "";
      } else {
        if (obj instanceof Array) {
          o = [];
          for (var i = 0, len = obj.length; i < len; i++) {
            o.push(this.clone_str(obj[i]));
          }
        } else {
          o = {};
          for (var k in obj) {
            if (obj[k] instanceof Array) {
              o[k] = this.clone_str([]);
            } else {
              o[k] = this.clone_str(obj[k]);
            }
          }
        }
      }
      break;
    default:
      o = obj;
      break;
  }
  return o;
};

//表单重置
let formReset = function (formParam) {
  Object.keys(formParam).forEach(function (key) {
    // 可进行逻辑判断，或者重新赋值
    if (typeof formParam[key] == "string") {
      formParam[key] = "";
    } else if (typeof formParam[key] == "number") {
      formParam[key] = "";
    } else {
      formParam[key] = [];
    }
  });
};

//构造表单formParam表单的参数，formParamDefault表单默认参数,exclude排除的参数
let formData = function (formParam, formParamDefault, exclude) {
  var excludeParam = exclude ? exclude : "";
  var param = new FormData();
  excludeParam = excludeParam.split(",");
  for (let key in formParam) {
    for (let k in formParamDefault) {
      if (key == k) {
        var flag = true; //判断是否是排除的参数
        excludeParam.forEach(e => {
          if (e == key) {
            flag = false;
          }
        });
        if (flag) {
          param.append(key, formParam[key]);
        }
      }
    }
  }

  return param;
};

//时间格式化
let dateFormat = function (fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
    }
  }
  return fmt;
};
//时间戳转时间类型
let getTime = function (data, type) {
  var _data = data;
  //如果是13位正常，如果是10位则需要转化为毫秒
  if (String(data).length == 13) {
    _data = data;
  } else {
    _data = data * 1000;
  }
  const time = new Date(_data);
  const Y = time.getFullYear();
  const Mon = time.getMonth() + 1;
  const Day = time.getDate();
  const H = time.getHours();
  const Min = time.getMinutes();
  const S = time.getSeconds();
  //自定义选择想要返回的类型
  if (type == "Y") {
    return `${Y}-${Mon}-${Day}`;
  } else if (type == "H") {
    return `${H}:${Min}:${S}`;
  } else {
    return `${Y}-${Mon}-${Day} ${H}:${Min}:${S}`;
  }
};
//字符串转时间类型
let stringToData = function (val) {
  var v = val.replace(/-/g, "/");
  return new Date(v);
};

// 设置表格的最大高度
let setTableMaxHeight = function(noPage) {
  var height = document.getElementById("manage").clientHeight;
  var conditionHeight = document.getElementsByClassName("condition")[0] ?
    document.getElementsByClassName("condition")[0].clientHeight : 0; //条件框高度
  var marginBottom = 12; //筛选条件和表格的距离
  if (noPage) {
    return height - conditionHeight - marginBottom;
  } else {
    var pageHeight = 42; //分页的高度
    return height - conditionHeight - marginBottom - pageHeight;
  }
}

// 下载
let windowOpen = function(url, data) {
  let paramStr = '';
  if (data && Object.keys(data).length > 0) {
    for (let key in data) {
      paramStr += key + '=' + data[key] + "&";
    }
    paramStr = paramStr.substring(0, paramStr.length - 1);
  }

  window.open(url + "?" + paramStr);
};

// 浏览器判断
let browser = function () {
  let versions = (function () {
    var u = navigator.userAgent,
      app = navigator.appVersion;
    return {
      //移动终端浏览器版本信息
      trident: u.indexOf("Trident") > -1, //IE内核
      presto: u.indexOf("Presto") > -1, //opera内核
      webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
      gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android终端或者uc浏览器
      iPhone: u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf("iPad") > -1, //是否iPad
      webApp: u.indexOf("Safari") == -1 //是否web应该程序，没有头部与底部
    };
  })();
  let language = (navigator.browserLanguage || navigator.language).toLowerCase();

  return {
    version: versions,
    language: language
  };
};

// 获取uuid的方法
let uuid = function (len) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [], i;
  var radix = 16;
  if (len) len = 8;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

export {
  btnShow,
  notify,
  msgbox,
  loading,
  formRules,
  clone_str,
  formReset,
  formData,

  dateFormat,
  getTime,
  stringToData,

  setTableMaxHeight,
  windowOpen,
  browser,

  uuid,
};
